import { Controller, Get, Post, Body, Param, Delete, Put, UseGuards, Query, BadRequestException, NotFoundException } from '@nestjs/common';
import { QuestionGroupService } from './question-group.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/roles.decorator';

@Controller('question-group')
@UseGuards(JwtAuthGuard, RolesGuard)
export class QuestionGroupController {
  constructor(private readonly QuestionGroupService: QuestionGroupService) {}

  @Post()
  @Roles('ADMIN')
  async create(@Body() createQuestionGroupDto: {
    name: string;
    description?: string;
    questions: string[];
    type?: string;
  }) {
    return this.QuestionGroupService.create(createQuestionGroupDto);
  }

  @Get()
  async findAll(@Query('type') type?: string) {
    return this.QuestionGroupService.findAll(type);
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    try {
      return await this.QuestionGroupService.findOne(id);
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw new NotFoundException(`题目组 ID ${id} 不存在`);
      }
      throw error;
    }
  }

  @Put(':id')
  @Roles('ADMIN')
  async update(
    @Param('id') id: string,
    @Body() updateQuestionGroupDto: {
      name?: string;
      description?: string;
      questions?: string[];
      type?: string;
    }
  ) {
    try {
      return await this.QuestionGroupService.update(id, updateQuestionGroupDto);
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw new NotFoundException(`题目组 ID ${id} 不存在`);
      }
      throw error;
    }
  }

  @Delete(':id')
  @Roles('ADMIN')
  async remove(@Param('id') id: string) {
    try {
      await this.QuestionGroupService.remove(id);
      return { code: 200, message: '删除成功' };
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw new NotFoundException(`题目组 ID ${id} 不存在`);
      }
      throw error;
    }
  }

  @Post(':id/questions')
  @Roles('ADMIN')
  async addQuestions(
    @Param('id') id: string,
    @Body('questionIds') questionIds: string[]
  ) {
    try {
      return await this.QuestionGroupService.addQuestions(id, questionIds);
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw new NotFoundException(`题目组 ID ${id} 不存在`);
      }
      throw error;
    }
  }

  @Delete(':id/questions/:questionId')
  @Roles('ADMIN')
  async removeQuestion(
    @Param('id') id: string,
    @Param('questionId') questionId: string
  ) {
    try {
      return await this.QuestionGroupService.removeQuestion(id, questionId);
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw new NotFoundException(error.message);
      }
      throw error;
    }
  }
}